package com.fyf.game.net;

import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicLong;

import org.je.log.JLog;
import org.je.util.DynBuffer;
import org.je.util.NumberUtil;

/**
 * @author fanyifeng
 */
public class DataAnalyzer
{
	private final DynBuffer	buffer;
	private int				blockLength	= -1;		// -1表示没有找到长度
	private boolean			needClose	= false;
	private ReceiveHandler	handler;
	private Sender		sender;
	private AtomicLong		successReadMsgCount;

	public DataAnalyzer(ReceiveHandler handler, Sender sender, AtomicLong successReadMsgCount) {
		this.handler = handler;
		this.sender = sender;
		buffer = new DynBuffer();
		this.successReadMsgCount = successReadMsgCount;
	}

	public void saveAndAnalyse(ByteBuffer temp) {
		if (!needClose)
			buffer.append(temp.array(), 0, temp.position());
		while (needClose == false && analyse()) {
			successReadMsgCount.incrementAndGet();
		}
	}

	private boolean analyse() {
		if (blockLength == -1) {
			if (buffer.size() < 10) {
				return false;
			} else {
				byte[] b = buffer.array();
				if (b[0] != 'm' || b[1] != 'm' || b[2] != '@' || b[3] != 'f' || b[4] != 'y' || b[5] != 'f') {
					JLog.error("协议错误，格式不正确: " + new String(b, 0, 6));
					needClose = true;
					return true;
				}
				blockLength = NumberUtil.bytes2int(b, 6);
				if (blockLength == 10) {
					needClose = true;
					return true;
				}
			}
		}
		if (buffer.size() >= blockLength) {
			String message = makeMessage();
			if (handler != null) {
				handler.onReceive(message, sender);
			}
			buffer.delete(0, blockLength);
			blockLength = -1;
			return true;
		}
		return false;
	}

	private String makeMessage() {
		try {
			return new String(buffer.array(), 10, blockLength - 10, "utf-8");
		} catch (Exception ex) {
			JLog.error(ex);
			return new String(buffer.array(), 10, blockLength - 10);
		}
	}

	public boolean needClose() {
		return needClose;
	}

	public String senderID() {
		return sender.getID();
	}
}
